package com.odontosis.view.login;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.odontosis.entidade.Usuario;
import com.odontosis.service.UsuarioService;
import com.odontosis.util.StringUtilsOdontosis;
import com.odontosis.view.OdontosisForm;

/**
 * Form para Login
 * @author pablo
 *
 */
public class FormLogin extends OdontosisForm {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String login;
	
	private String senha;
	

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getSenha() {
		return senha;
	}

	public void setSenha(String senha) {
		this.senha = senha;
	}
	
	@Override
	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		ActionErrors errors = new ActionErrors();
		ActionMessages messages = new ActionMessages();
		Collection<String> erros = null;

		if(!(StringUtilsOdontosis.isVazia(getLogin()) && StringUtilsOdontosis.isVazia(getSenha()))){
			try{
			UsuarioService service = new UsuarioService();
			Usuario usuario = service.buscarPorLogin(getLogin());
			if(usuario == null || !usuario.getSenha().equals(getSenha())){
				messages.add("login", new ActionMessage(
				"Login ou senha inválidos."));
			}
			}catch (Exception e) {
				e.printStackTrace();
			}
		}


		if (messages.size() > 0 && getMetodo() != null) {
			errors.add(messages);
			erros = new ArrayList<String>();
			for (Iterator iterator = messages.get(); iterator.hasNext();) {
				ActionMessage string = (ActionMessage) iterator.next();
				erros.add(string.getKey());
			}
			request.setAttribute("mensagens", erros);
			return errors;
		} else {
			request.setAttribute("mensagens", null);
			return super.validate(mapping, request);
		}

	}

	
}
